import { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { DownOutlined } from '@ant-design/icons';
import { Button, Dropdown, Menu, Modal, message, Form, Input } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import {
  codegroupSearch,
  codegroupCreateCoupon,
  redeemActivateCode,
  exportDetail,
  exportCode,
  codegroupExport,
  codegroupResetTask,
  batchDestroy,
} from '@/services/batchManage';
import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';

import styles from './style.less';

const { confirm } = Modal;

const SensitizeManageList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [exportLoading, setExportLoading] = useState<boolean>(false);

  const [modalNumForm] = Form.useForm();
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelNumVisible, setModelNumVisible] = useState<boolean>(false);
  const [modelCodeVisible, setModelCodeVisible] = useState<boolean>(false);
  const [modalCodeForm] = Form.useForm();

  // 提交
  const handleOperate = async (record: any, type: string) => {
    if (type === '批量激活') {
      modalCodeForm.setFieldsValue({
        id: record?.id || '',
        activityId: record?.activityId || '',
        storeId: '',
        orderId: '',
        productPrice: '',
        productId: '',
        activationKS: '',
        activationJS: '',
      });
      setModelCodeVisible(true);
      return;
    }
    if (type === '生成码') {
      modalNumForm.setFieldsValue({
        id: record.id,
        num: '',
      });
      setModelNumVisible(true);
      return;
    }

    confirm({
      content: `确认${type} 批次ID：${record.groupId}？`,
      async onOk() {
        if (type === '批量销毁') {
          const { code, data } = await batchDestroy({ id: record.id });
          if (code === 200 && data) {
            message.success('操作成功');
            actionRef?.current?.reloadAndRest?.();
          } else {
            message.error('批量销毁失败');
          }
        }

        if (type === '导出明细') {
          try {
            const resUpdate = await exportDetail({ id: record.id });
            const url = window.URL.createObjectURL(resUpdate.data);
            const link = document.createElement('a');
            link.style.display = 'none';
            const Disposition = resUpdate?.Disposition || '';
            if (!Disposition) {
              message.error('暂无数据');
              return;
            }
            link.download =
              decodeURIComponent(Disposition?.split(`filename*=utf-8''`)[1]) || '导出列表'; // 下载的文件名称
            link.href = url;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            message.success('导出成功');
          } catch (error) {
            message.error('导出失败');
          }
        }

        if (type === '导出码') {
          try {
            const resUpdate = await exportCode({ id: record.id });
            const url = window.URL.createObjectURL(resUpdate.data);
            const link = document.createElement('a');
            link.style.display = 'none';
            const Disposition = resUpdate?.Disposition || '';
            if (!Disposition) {
              message.error('暂无数据');
              return;
            }
            link.download =
              decodeURIComponent(Disposition?.split(`filename*=utf-8''`)[1]) || `${type}`; // 下载的文件名称
            link.href = url;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            message.success('导出成功');
          } catch (error) {
            message.error('导出失败');
          }
        }
      },
      onCancel() {},
    });
  };

  // 跳编辑页
  const hanldleEdit = (record: any) => {
    history.push(`/profile/batchManage/modify/${record.id}`);
  };

  const getItems = (record: any) => {
    return (
      <Menu>
        <Menu.Item key="refresh1">
          <a onClick={() => handleOperate(record, '生成码')}>生成码</a>
        </Menu.Item>
        {/* <Menu.Item key="refresh2">
          <a onClick={() => handleOperate(record, '导出明细')}>导出明细</a>
        </Menu.Item> */}
        <Menu.Item key="sort">
          <a onClick={() => handleOperate(record, '导出码')}>导出码</a>
        </Menu.Item>
        {record.needActiveCode === 1 && (
          <Menu.Item key="file">
            <a onClick={() => handleOperate(record, '批量激活')}>批量激活</a>
          </Menu.Item>
        )}
        {Number(record.codeCount) > 0 && (
          <Menu.Item key="batch">
            <a onClick={() => handleOperate(record, '批量销毁')}>批量销毁</a>
          </Menu.Item>
        )}
      </Menu>
    );
  };

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: '活动Id',
      dataIndex: 'activityId',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '批次ID',
      dataIndex: 'groupId',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '合同编号',
      dataIndex: 'contractNo',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '申请人',
      dataIndex: 'groupOwner',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '批次名称',
      dataIndex: 'groupName',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    // 表格
    {
      title: '活动id',
      dataIndex: 'activityId',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '批次ID',
      dataIndex: 'groupId',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '批次名称',
      dataIndex: 'groupName',
      ellipsis: true,
      width: 190,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '兑换码有效期开始时间',
      dataIndex: 'couponCodeStartTime',
      ellipsis: true,
      width: 160,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '兑换码有效期结束时间',
      dataIndex: 'couponCodeEndTime',
      ellipsis: true,
      width: 160,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '是否需要激活码',
      dataIndex: 'needActiveCode',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        0: { text: '不需要' },
        1: { text: '需要' },
      },
    },
    {
      title: '激活码前缀',
      dataIndex: 'activeCodePrex',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活码开始码',
      dataIndex: 'activeCodeFrirst',
      ellipsis: true,
      width: 170,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活码结束码',
      dataIndex: 'activeCodeLast',
      ellipsis: true,
      width: 170,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '是否激活限制',
      dataIndex: 'activeLimitation',
      ellipsis: true,
      width: 110,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        0: { text: '不限制' },
        1: { text: '限制' },
      },
    },
    {
      title: '可激活餐厅号',
      dataIndex: 'storeIds',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活码产品Id',
      dataIndex: 'productId',
      ellipsis: true,
      width: 110,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活码产品金额（订单单价）',
      dataIndex: 'productPrice',
      ellipsis: true,
      width: 200,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活码效期开始时间',
      dataIndex: 'activeCodeStartTime',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活码效期结束时间',
      dataIndex: 'activeCodeEndTime',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '生成量',
      dataIndex: 'codeCount',
      ellipsis: true,
      width: 65,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '合同编号',
      dataIndex: 'contractNo',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '申请人',
      dataIndex: 'groupOwner',
      ellipsis: true,
      width: 90,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 120,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            <a onClick={() => hanldleEdit(record)}>修改</a>&nbsp;&nbsp;
            <Dropdown overlay={getItems(record)}>
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: any = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await codegroupSearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  // 导出
  const handleOutput = async () => {
    setExportLoading(true);
    try {
      const resUpdate = await codegroupExport();
      const url = window.URL.createObjectURL(resUpdate.data);
      const link = document.createElement('a');
      link.style.display = 'none';
      const Disposition = resUpdate?.Disposition || '';
      if (!Disposition) {
        message.error('暂无数据');
        return;
      }
      link.download = decodeURIComponent(Disposition?.split(`filename*=utf-8''`)[1]) || '导出列表'; // 下载的文件名称
      link.href = url;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      setExportLoading(false);
      message.success('导出成功');
    } catch (error) {
      setExportLoading(false);
      message.error('导出失败');
    }
  };

  const handlRefresh = async () => {
    const { code, data } = await codegroupResetTask();
    if (code === 200 && data) {
      message.success('刷新缓存成功');
      actionRef?.current?.reloadAndRest?.();
    }
  };

  const toAddPage = async () => {
    history.push(`/profile/batchManage/add`);
  };

  const handleNumCancel = () => {
    setModelNumVisible(false);
    modalNumForm.resetFields();
  };

  const handleNumOK = () => {
    modalNumForm.validateFields().then(async (values) => {
      setConfirmLoad(true);
      const { code, data } = await codegroupCreateCoupon({ ...values });
      if (code === 200 && data) {
        // message.success('操作成功');
        message.info(
          '生成中（如果数据量过大请耐心等待,点查询等生产量和结束码更新后再操作,防止多次生成）',
        );
        modalNumForm.resetFields();
        setModelNumVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  const subtract = (num1: number, num2: number) => {
    // 将数字转换为字符串
    const str1 = num1.toString();
    const str2 = num2.toString();

    // 使用split()方法将字符串分割为数组
    const num1Arr = str1.split(',');
    const num2Arr = str2.split(',');

    // 对两个数组进行排序
    const sortedArrays = [num1Arr, num2Arr].sort((a, b) => a.length - b.length);

    // 使用map()方法将较小的数组中的每个元素与较大的数组中的对应元素相减
    const difference = sortedArrays[0].map(
      (item, index) => parseInt(item) - parseInt(sortedArrays[1][index]),
    );

    // 使用join()方法将结果数组连接成一个字符串
    const resultStr = difference.join('');

    // 使用parseInt()方法将结果字符串转换为整数
    const result = parseInt(resultStr);

    return result;
  };

  const subtractBro = (num1: number, num2: number) => {
    // 将数字转换为字符串
    const str1 = num1.toString();
    const str2 = num2.toString();

    // 使用split()方法将字符串分割为数组
    const num1Arr = str1.split(',');
    const num2Arr = str2.split(',');

    // 获取两个数组中的最大长度
    const maxLength = Math.max(num1Arr.length, num2Arr.length);

    // 将较短的数组用0填充，使其长度与较长数组相同
    while (num1Arr.length < maxLength) {
      num1Arr.push('0');
    }
    while (num2Arr.length < maxLength) {
      num2Arr.push('0');
    }

    // 使用reduce()方法计算两个数组的差值
    const difference = num1Arr.reduce((acc, cur, index) => {
      return acc + (parseInt(cur) - parseInt(num2Arr[index]));
    }, 0);

    // 将差值转换为字符串并返回
    return difference.toString();
  };

  const calculateDifference = (number1: number, number2: number) => {
    const num1Str = number1.toString().split(',');
    const num2Str = number2.toString().split(',');

    const num1Arr = num1Str.map((item) => parseInt(item));
    const num2Arr = num2Str.map((item) => parseInt(item));

    const maxLength = Math.max(num1Arr.length, num2Arr.length);

    const num1 = num1Arr.slice(0, maxLength);
    const num2 = num2Arr.slice(0, maxLength);

    const difference = num1.reduce((acc, cur, index) => acc + (cur - num2[index]), 0);

    return difference.toString();
  };

  const subtractLongNumbers = (num1: string, num2: string) => {
    const maxLength = Math.max(num1.length, num2.length);
    const paddedNum1 = num1.padStart(maxLength, '0');
    const paddedNum2 = num2.padStart(maxLength, '0');

    let difference = '';
    let borrow = 0;

    for (let i = maxLength - 1; i >= 0; i--) {
      const digit1 = parseInt(paddedNum1[i]);
      const digit2 = parseInt(paddedNum2[i]);

      let digitDifference = digit1 - digit2 - borrow;
      if (digitDifference < 0) {
        digitDifference += 10;
        borrow = 1;
      } else {
        borrow = 0;
      }

      difference = digitDifference.toString() + difference;
    }

    if (Number(difference).toString().length > 18) {
      message.error('激活码结束号必须大于激活码开始号');
      return '';
    }
    return Number(difference) + 1;
  };

  const handleCodeCancel = () => {
    setModelCodeVisible(false);
    modalCodeForm.resetFields();
  };

  const handleCodeOK = () => {
    modalCodeForm.validateFields().then(async (values) => {
      if (Number(values.activationKS) > Number(values.activationJS)) {
        message.error('激活码结束号必须大于激活码开始号');
        return;
      }

      setConfirmLoad(true);
      console.log('批量激活--values', values);
      confirm({
        title: `激活的数量为${subtractLongNumbers(values.activationJS, values.activationKS)}`,
        okText: '确认',
        async onOk() {
          const { code, data } = await redeemActivateCode({ ...values });
          if (code === 200 && data) {
            message.success('批量激活完成,详细信息请看日志');
            actionRef?.current?.reloadAndRest?.();
            setModelCodeVisible(false);
            modalCodeForm.resetFields();
          } else {
            message.error('批量激活失败');
          }
          setConfirmLoad(false);
        },
        onCancel() {
          setConfirmLoad(false);
        },
      });
    });
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.CodegroupListItem>
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          toolBarRender={() => [
            <Button loading={exportLoading} type="primary" key="add" onClick={() => handleOutput()}>
              导出
            </Button>,
            <Button type="primary" key="add" onClick={() => handlRefresh()}>
              刷新缓存
            </Button>,
            <Button type="primary" key="add" onClick={() => toAddPage()}>
              新增
            </Button>,
          ]}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />
        <Modal
          title="生成码数量"
          width={520}
          open={modelNumVisible}
          onOk={handleNumOK}
          onCancel={handleNumCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalNumForm}
            initialValues={{
              id: '',
              num: '',
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item
              label="数量"
              name="num"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
              style={{ width: 400 }}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="批量激活"
          width={520}
          open={modelCodeVisible}
          onOk={handleCodeOK}
          onCancel={handleCodeCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalCodeForm}
            initialValues={{
              id: '',
              num: '',
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item label="activityId" name="activityId" hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item
              label="门店号"
              name="storeId"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="storeId" />
            </Form.Item>
            <Form.Item
              label="订单号"
              name="orderId"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="orderId" />
            </Form.Item>
            <Form.Item label="订单单价(单位分)" name="productPrice">
              <Input placeholder="Price(没配的,可不填)" />
            </Form.Item>
            <Form.Item label="产品ID" name="productId">
              <Input placeholder="productId(没配的,可不填)" />
            </Form.Item>
            <Form.Item
              label="激活码开始号"
              name="activationKS"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="ActiveCodeFrirst" />
            </Form.Item>
            <Form.Item
              label="激活码结束号"
              name="activationJS"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="ActiveCodeLast" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageList;
